package cn.dzhang.rcp.hyperbola;

import org.eclipse.core.runtime.preferences.ConfigurationScope;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;

import cn.dzhang.rcp.hyperbola.dialogs.LoginDialog;
import cn.dzhang.rcp.hyperbola.preferences.GeneralPreferencePage;

/**
 * This class controls all aspects of the application's execution
 */
public class Application implements IApplication {

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.
	 * IApplicationContext)
	 */
	@Override
	public Object start(IApplicationContext context) throws Exception {
		Display display = PlatformUI.createDisplay();

		try {
			if (!login()) {
				return IApplication.EXIT_OK;
			}
			int returnCode = PlatformUI.createAndRunWorkbench(display,
					new ApplicationWorkbenchAdvisor());
			if (returnCode == PlatformUI.RETURN_RESTART) {
				return IApplication.EXIT_RESTART;
			} else {
				return IApplication.EXIT_OK;
			}
		} finally {
			display.dispose();
		}

	}

	/**
	 * Login Server
	 * 
	 * @return <code>true</code> if login failed, or <code>false</code>
	 */
	private boolean login() {
		IEclipsePreferences preferences = ConfigurationScope.INSTANCE
				.getNode(Activator.PLUGIN_ID);

		boolean autoLogin = preferences.getBoolean(
				GeneralPreferencePage.AUTO_LOGIN, false);
		if (autoLogin) {
			return true;
		} else {
			LoginDialog dialog = new LoginDialog(null);

			int result = dialog.open();
			if (result != Window.OK) {
				return false;
			}
		}
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.equinox.app.IApplication#stop()
	 */
	@Override
	public void stop() {
		if (!PlatformUI.isWorkbenchRunning()) {
			return;
		}
		final IWorkbench workbench = PlatformUI.getWorkbench();
		final Display display = workbench.getDisplay();
		display.syncExec(new Runnable() {
			@Override
			public void run() {
				if (!display.isDisposed()) {
					workbench.close();
				}
			}
		});
	}
}
